/**
 * Copyright By Grandsoft Company Limited.  
 * 2013-6-13 上午11:30:05
 */
package com.glodon.ggzy.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.glodon.ggzy.core.utils.Constants;
import com.glodon.ggzy.core.utils.Tools;
import com.glodon.ggzy.entity.JgUser;
import com.glodon.ggzy.user.service.IJgptUserService;
import com.glodon.ggzy.vo.AuthorityMenu;

@Controller
public class LoginController {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	IJgptUserService jgptUserService;

	@RequestMapping("/login")
	public String login(Model model, String userName, String role) {
		return "/login";
	}

	@RequestMapping("/jgpt_logout")
	public String logout(Model model, HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setAttribute(Constants.user_session_jg_key, null);
		return "redirect:login.do";
	}

	@RequestMapping("/landing")
	public String landing(Model model, HttpServletRequest request, HttpServletResponse response, String userName, String password) {
		if ("super".equals(userName) && "super".equals(password)) {
			HttpSession session = request.getSession();
			session.setAttribute(Constants.user_session_super_key, new JgUser());
			return "redirect:user/jgpt_user_list.do";
		}

		boolean checkUser = jgptUserService.checkUser(userName, password);

		if (!checkUser) {
			model.addAttribute("error", "用户名或者密码输入错误,请检查!");
			model.addAttribute("userName", userName);
			return "/login";
		}
		//把当前的用户放入session中
		JgUser findUser = jgptUserService.findUser(userName, password);
		HttpSession session = request.getSession();
		session.setAttribute(Constants.user_session_jg_key, findUser);

		//取当前用户的权限列表
		List<AuthorityMenu> listAuthorithMenu = jgptUserService.queryAuthorityByUserId(findUser.getId());
		model.addAttribute("authList", listAuthorithMenu);

		if (listAuthorithMenu.size() != 0) {
			AuthorityMenu authorityMenu = listAuthorithMenu.get(0);
			return "redirect:jgpt/" + authorityMenu.getMenuUrl();
		} else {
			Tools.repsonseJsAlert("您当前没有查看监管数据的权限，请联系管理员分配！", response);
		}

		return "/login";
	}
}
